package com.zyh.thread.demo5;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author zyh
 * @Date 2024/8/8 16:23
 * @Description Lock 锁 模拟火车站卖票
 */

public class ThreadDemo5 {
    public static void main(String[] args) {
        MyTask myTask = new MyTask();
        for (int i = 0; i < 5; i++) {
            new Thread(myTask,"窗口"+(i+1)).start();
        }
    }
}
class MyTask implements Runnable{
    private int num=100;
    Lock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();
                if (num<=0){
                    break;
                }
                System.out.println(Thread.currentThread().getName()+"正在卖第"+num+"张票");
                num--;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
